package com.it.schoolbookshop_back.utils;

import com.it.schoolbookshop_back.entities.dto.CreateUserDTO;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.enums.UserRoleEnums;
import com.it.schoolbookshop_back.enums.UserStatusEnums;
import com.it.schoolbookshop_back.service.UserService;

/**
 * 用户验证工具类
 * 提供用户数据验证相关的静态方法
 */
public class UserValidationUtils {

    /**
     * 验证用户创建参数
     * @param createUserDTO 用户创建DTO
     * @param userService 用户服务
     * @return 验证失败返回错误信息，成功返回null
     */
    public static Result<?> validateCreateUser(CreateUserDTO createUserDTO, UserService userService) {
        // 验证用户名
        if (createUserDTO.getUsername() == null || createUserDTO.getUsername().trim().isEmpty()) {
            return Result.validateFailed("用户名不能为空");
        }
        
        // 验证角色
        if (createUserDTO.getRole() == null || createUserDTO.getRole().trim().isEmpty()) {
            return Result.validateFailed("角色不能为空");
        }
        
        // 验证角色是否有效
        try {
            UserRoleEnums.valueOf(createUserDTO.getRole().toUpperCase());
        } catch (IllegalArgumentException e) {
            return Result.validateFailed("无效的角色，必须是 'STUDENT' 或 'ADMIN'");
        }
        
        // 检查用户名是否已存在
        if (userService.isUsernameExists(createUserDTO.getUsername())) {
            return Result.validateFailed("该用户名已被注册");
        }
        
        // 验证通过
        return null;
    }
    
    /**
     * 创建用户对象
     * @param createUserDTO 创建用户DTO
     * @return 用户对象
     */
    public static User createUserFromDTO(CreateUserDTO createUserDTO) {
        User user = new User();
        user.setUsername(createUserDTO.getUsername());
        // 设置默认密码为123456
        user.setPassword("123456");
        user.setRole(createUserDTO.getRole().toUpperCase());
        user.setStatus(UserStatusEnums.ACTIVE.name()); // 1 表示激活状态
        return user;
    }
} 